package com.aliyun.core;

import com.aliyun.core.pojo.Authority;
import org.springframework.util.Assert;

import java.util.Date;

public abstract class AliyunAbstractContext implements AliyunContext{

    protected abstract ThreadLocal<Authority> getThreadLocal();

    /**
     * 设置 Security Token
     * @param securityToken 安全令牌
     */
    public void setSecurityToken(String securityToken) {
        Assert.notNull(securityToken, "securityToken is null");
        Authority authority = getAuthority();
        authority.setSecurityToken(securityToken);
        setAuthority(authority);
    }

    /**
     * 设置 Authority 对象
     * @param authority STS认证对象
     */
    public void setAuthority(Authority authority) {
        clearContext();
        Assert.notNull(authority, "authority is null");
        getThreadLocal().set(authority);
    }

    /**
     * 获取临时凭证id
     */
    public String getAccessKeyId() {
        return getAuthority().getAccessKeyId();
    }

    /**
     * 获取临时凭证secret
     */
    public String getAccessKeySecret() {
        return getAuthority().getAccessKeySecret();
    }

    private Authority getAuthority() {
        return getThreadLocal().get();
    }

    /**
     * 获取 Security Token
     * @return 安全令牌
     */
    public String getSecurityToken() {
        return getThreadLocal().get().getSecurityToken();
    }

    /**
     * 清除上下文
     */
    public void clearContext() {
        getThreadLocal().remove();
    }

}
